# Oracle连接池紧急修复脚本
# 用于解决ORA-50012连接池耗尽问题

param(
    [string]$ServiceName = "LzfyHisService",
    [int]$MaxPoolSize = 100,
    [int]$MinPoolSize = 10,
    [int]$ConnectionTimeout = 60,
    [switch]$RestartService = $true,
    [switch]$TestConnection = $true,
    [switch]$ClearPools = $true
)

Write-Host "🔧 Oracle连接池紧急修复脚本" -ForegroundColor Green
Write-Host "=================================" -ForegroundColor Green

# 1. 检查服务状态
Write-Host "📊 检查服务状态..." -ForegroundColor Yellow
$service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($service) {
    Write-Host "✅ 服务 '$ServiceName' 状态: $($service.Status)" -ForegroundColor Green
} else {
    Write-Host "❌ 服务 '$ServiceName' 未找到" -ForegroundColor Red
    exit 1
}

# 2. 备份配置文件
$configPath = "appsettings.json"
$backupPath = "appsettings.json.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Write-Host "💾 备份配置文件到: $backupPath" -ForegroundColor Yellow
Copy-Item $configPath $backupPath -Force

# 3. 优化连接池配置
Write-Host "⚙️ 优化Oracle连接池配置..." -ForegroundColor Yellow
$config = Get-Content $configPath | ConvertFrom-Json

# 更新Oracle连接字符串配置
$oracleConnection = $config.ConnectionStrings.HisOracleConnection
$newOracleConnection = $oracleConnection -replace "Max Pool Size=\d+", "Max Pool Size=$MaxPoolSize" `
    -replace "Min Pool Size=\d+", "Min Pool Size=$MinPoolSize" `
    -replace "Connection Timeout=\d+", "Connection Timeout=$ConnectionTimeout"

$config.ConnectionStrings.HisOracleConnection = $newOracleConnection

# 保存更新后的配置
$config | ConvertTo-Json -Depth 10 | Set-Content $configPath
Write-Host "✅ 连接池配置已更新: Max Pool Size=$MaxPoolSize, Min Pool Size=$MinPoolSize, Connection Timeout=$ConnectionTimeout" -ForegroundColor Green

# 4. 清理Oracle连接池
if ($ClearPools) {
    Write-Host "🧹 清理Oracle连接池..." -ForegroundColor Yellow
    try {
        # 使用PowerShell调用Oracle.ManagedDataAccess来清理连接池
        $oracleAssemblyPath = Get-ChildItem -Path ".\*.dll" -Recurse | Where-Object { $_.Name -like "*Oracle.ManagedDataAccess*" } | Select-Object -First 1
        if ($oracleAssemblyPath) {
            Add-Type -Path $oracleAssemblyPath.FullName
            [Oracle.ManagedDataAccess.Client.OracleConnection]::ClearAllPools()
            Write-Host "✅ Oracle连接池已清理" -ForegroundColor Green
        } else {
            Write-Host "⚠️ 未找到Oracle.ManagedDataAccess程序集，跳过清理" -ForegroundColor Yellow
        }
    } catch {
        Write-Host "⚠️ 清理连接池时出错: $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

# 5. 重启服务
if ($RestartService) {
    Write-Host "🔄 重启服务..." -ForegroundColor Yellow
    try {
        Stop-Service $ServiceName -Force
        Start-Sleep -Seconds 5
        Start-Service $ServiceName
        Start-Sleep -Seconds 10
        
        $service = Get-Service -Name $ServiceName
        if ($service.Status -eq "Running") {
            Write-Host "✅ 服务已成功重启" -ForegroundColor Green
        } else {
            Write-Host "❌ 服务重启失败，当前状态: $($service.Status)" -ForegroundColor Red
        }
    } catch {
        Write-Host "❌ 重启服务时出错: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 6. 测试连接
if ($TestConnection) {
    Write-Host "🧪 测试Oracle连接..." -ForegroundColor Yellow
    $testUrl = "http://localhost:5000/api/health/oracle-test-connection"
    try {
        $response = Invoke-RestMethod -Uri $testUrl -Method Get -TimeoutSec 30
        if ($response.success) {
            Write-Host "✅ Oracle连接测试成功" -ForegroundColor Green
        } else {
            Write-Host "❌ Oracle连接测试失败: $($response.message)" -ForegroundColor Red
        }
    } catch {
        Write-Host "❌ 连接测试失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "🎉 Oracle连接池修复完成" -ForegroundColor Green
Write-Host "=================================" -ForegroundColor Green